package org.flow.basic.doubts.clazz;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 * 自定义类加载器
 *
 * @author xl-9527
 * @since 2024/10/26
 **/
public class CustomClazzLoader extends ClassLoader {

    private final Logger log = LoggerFactory.getLogger(CustomClazzLoader.class);

    private final String rootPath;

    public CustomClazzLoader() {
        this.rootPath = "/Users/a1-6/Desktop/project/idea/back/common-study-demo/study-basic/src/main/java/org/flow/basic/doubts/clazz/";
    }

    @Override
    public Class<?> findClass(final String name) {
        log.info("当前类的加载类 -> {}", this.getClass().getClassLoader().getName());
        log.info("当前类的父类加载器 -> {}", this.getParent().getName());
        try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(rootPath + name + ".class"))) {
            final byte[] allBytes = bis.readAllBytes();
            return super.defineClass(null, allBytes, 0, allBytes.length);
        } catch (Exception e) {
            log.error("error -> {}", e.getMessage());
        }
        return null;
    }
}
